import http from './http'

export async function wxAuth() {
  const { data } = await http.get(
    `/api/bactroban-bus/wxAuth?url=${window.location.href}`,
  )
  window.location.href = data
}

export function isWeixin() {
  const ua: any = window.navigator.userAgent.toLowerCase()
  return ua.match(/MicroMessenger/i) === 'micromessenger'
}

export async function initWXConfig(options?: {
  title?: string
  desc?: string
  link?: string
  imgUrl?: string
}) {
  if (!isWeixin())
    return

  const { data } = await http.get(
    `/api/bactroban-bus/jssdk?url=${encodeURIComponent(window.location.href)}`,
  )
  const { wx } = window

  wx?.config({
    debug: false,
    appId: data.appId,
    timestamp: data._wxTimestamp,
    nonceStr: data._wxNoncestr,
    signature: data._wxSignature,
    jsApiList: [
      'onMenuShareAppMessage',
      'onMenuShareTimeline',
      'updateAppMessageShareData',
      'updateTimelineShareData',
    ],
  })

  wx?.ready(() => {
    const uid = localStorage.getItem('userId')
    const shareData = {
      title: '疯狂动物城大巴来了，快上车！',
      desc: '召集好友一起来玩，赢上海奇妙之旅~',
      link: `${window.location.origin}?uid=${uid}&platform=${window?.platform || 'WX'
      }`,
      imgUrl: 'https://bactroban-bus.hawnlink.cn/share.jpg?v=1.0.0',
      ...options,
    }

    wx.onMenuShareAppMessage(shareData)
    wx.onMenuShareTimeline(shareData)
    wx.updateAppMessageShareData(shareData)
    wx.updateTimelineShareData(shareData)

    window.WeixinJSBridge.call('showOptionMenu')
  })
  wx?.error((error: any) => {
    console.log('wx.error is', error)
    // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
  })
}

// 判断数字是否在某个区间
export function isInRange(num: number, start: number, end: number): boolean {
  // 如果num小于start或者大于end，返回false
  if (num < start || num > end) {
    return false
  }
  // 否则返回true
  return true
}

// 获取平台关键字
export function getCurrentEnvironment() {
  const userAgent = navigator.userAgent.toLowerCase()
  if (userAgent.includes('alipay')) {
    return 'ZHIFUBAO'
  }
  else if (userAgent.includes('baidu')) {
    return 'BAIDU'
  }
  else if (userAgent.includes('micromessenger')) {
    return 'WX'
  }
  else if (userAgent.includes('weibo')) {
    return 'WEIBO'
  }
  else if (userAgent.includes('toutiao')) {
    return 'DOUYIN'
  }
  else {
    return '未知环境'
  }
}

// 预加载图片
export async function PreLoadImages(paths: string[]) {
  let imageFetchCount: number = 0
  return new Promise((resolve) => {
    paths.forEach((path: string) => {
      const i = new Image()
      i.src = path
      i.onload = function () {
        imageFetchCount++
        if (imageFetchCount >= paths.length) {
          resolve(true)
        }
      }

      i.onerror = function (e) {
        resolve(e)
      }
    })
  })
}
